package ru.efko.dims.chart;

import java.util.ArrayList;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;

import ru.efko.dims.domain.SensorDevice;
import ru.efko.dims.util.ThreadLocalVariablesKeeper;
import android.content.Context;
import android.graphics.Color;

public class SensorValueChart extends AbstractDemoChart {
	
	private XYMultipleSeriesDataset dataSet;
	private SensorDevice sensorDevice; 
	private GraphicalView view;
	
	public SensorValueChart(){
		sensorDevice = ThreadLocalVariablesKeeper.getSensorDevice();
	}

	public String getName() {
		return "Dims functions";
	}

	public String getDesc() {
		return "The graphical representations of entering data";
	}

	/**
	 * Executes the chart demo.
	 * 
	 * @param context
	 *            the context
	 * @return the built intent
	 */
	public GraphicalView execute(Context context, int[] array){
		String[] titles = new String[] { "data" };
		List<double[]> x = new ArrayList<double[]>();
		List<double[]> values = new ArrayList<double[]>();
		int count = array.length;
		x.add(new double[count]);
		double[] dataValues = new double[count];
		values.add(dataValues);
		double max = Double.MIN_VALUE;
		double min = Double.MAX_VALUE;
		for (int i = 0; i < count; i++) {
			x.get(0)[i] = i;
			dataValues[i] = array[i];
			if (max < dataValues[i]) {
				max = dataValues[i];
			}
			if (min > dataValues[i]) {
				min = dataValues[i];
			}
		}
		int[] colors = new int[] { Color.GREEN };
		PointStyle[] styles = new PointStyle[] { PointStyle.POINT };
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
		setChartSettings(renderer, "Data", "Array count", "Value", 0, array.length, min,
				max, Color.DKGRAY, Color.DKGRAY);
		renderer.setXLabels(20);
		renderer.setYLabels(10);
		renderer.setShowLabels(true);
		renderer.setShowLegend(false);
		renderer.setApplyBackgroundColor(true);
		renderer.setBackgroundColor(Color.BLACK);
		renderer.setShowGrid(true);
		dataSet = buildDataset(titles, x, values);
		view = ChartFactory.getLineChartView(context, dataSet, renderer);
		return view;
	}

	public void updateDataSet(){
		 int[] data = sensorDevice.get_data();
		 int everyN = data.length/1900;
		 XYSeries series = dataSet.getSeriesAt(0);
		 series.clear();
		 for (int i = 0 ; i<data.length ; i+=everyN){
			 series.add(i, data[i]);
		 }
		 view.repaint();
	}

}